package com.tianheng.modbus.schedule;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/7/23 0023
 * since:      1.0.0.1
 * description:
 *
 **************************************************/
import com.tianheng.modbus.nettyservice.ModbusDeviceService;
import com.tianheng.modbus.nettyservice.Server;
import com.tianheng.modbus.util.BytesAndHex;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Component
public class ScheduleTask implements SchedulingConfigurer {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    private ModbusDeviceService modbusDeviceService;



    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        System.err.println("定时任务开始");
            modbusDeviceService.getDeviceAndOrder().forEach((item)->{
                scheduledTaskRegistrar.addTriggerTask(
                        () -> {
                            try {
//                              System.out.println( Thread.currentThread().getName());
                                String ip = "127.0.0.1";
                                Map<String, Channel> map = Server.getMap();
                                    if (map.get(ip) != null) {
                                        Channel ch = map.get(ip);
                                        String content = item.getOrder();
                                        System.out.println(Thread.currentThread().getName()+"--"+content);
                                        ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
                                        ch.writeAndFlush(buf);
                                    }

                            } catch (Exception e) {
                                e.printStackTrace();
                        }
                        },
                        triggerContext -> {
                            if (StringUtils.isEmpty(item)) {
                                LOGGER.error("计划任务为空");
                            }
                            return new CronTrigger("*/150 * * * * ?").nextExecutionTime(triggerContext);
                        }
                );
            });
    }
}
